package com.isunland.managesystem.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseListAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.entity.BillOriginal;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.RProInvoiceRecd;
import com.isunland.managesystem.entity.rOutappMain;
import com.isunland.managesystem.utils.MyUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@SuppressLint("NewApi") public class BillListFragment extends BaseListFragment {

  private BaseListAdapter mAdapter;
  private String mCustomerId;

  @Override public void onCreate(Bundle savedInstanceState) {
    mCustomerId = getArguments().getString(ContractPagerActivity.EXTRA_CUSTOMER_ID);
    super.onCreate(savedInstanceState);
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    // 执行完父类方法才存在mListView.
    super.onViewCreated(view, savedInstanceState);
    mListview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    mListview.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        mAdapter.notifyDataSetChanged();
      }
    });
  }

  @Override public String getUrl() {
    // Auto-generated method stub
    return ApiConst.URL_BILL_LIST;
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<String, String>();
    String memberCode = CurrentUser.newInstance(getActivity()).getMemberCode();
    params.put("curPage", "1");
    params.put("pageSize", "10000");
    params.put("memberCode", memberCode);
    params.put("minkindCode", memberCode + "-DJLB-IN-CGDDRK");
    params.put("moutkindCode", memberCode + "-DJLB-OUT-XSDDCK");
    params.put("minbillStatusCode", "undefined");
    params.put("moutbillStatus", "");
    params.put("customerId", mCustomerId);
    params.put("ifAllpay", "F");
    params.put("ifInvoiceFinished", "F");
    params.put("orderField", "order_no");
    params.put("orderSeq", "desc");
    params.put("type", "mobile");
    return params;
  }

  @Override public void resolveResponse(String arg0) {

    BillOriginal attendanceListOriginal = new Gson().fromJson(arg0, BillOriginal.class);

    List<rOutappMain> rows = attendanceListOriginal.getRows();
    // List<rOutappMain> rows = testData();
    setAdapter(rows);
  }

  private List<rOutappMain> testData() {
    List<rOutappMain> rows = new ArrayList<rOutappMain>();

    for (int i = 0; i < 20; i++) {
      // int suffix = (page - 1) * 20 + i;
      rOutappMain item = new rOutappMain();
      item.setId(UUID.randomUUID().toString());
      item.setMoutbillNo(i + "");
      item.setMcustomerName("谷歌" + i);
      item.setMoutappmanName("王亚南" + i);
      rows.add(item);
    }
    return rows;
  }

  private void setAdapter(List<rOutappMain> detail) {
    if (detail == null) {
      detail = new ArrayList<rOutappMain>();
    }

    if (mAdapter == null) {
      mAdapter = new BaseListAdapter<rOutappMain>(getActivity(), detail) {

        @Override
        public void bindData(int position, BaseListAdapter.ViewHolder vh, rOutappMain item) {
          vh.mTitleOneTv.setText(getContext().getString(R.string.inOutStoreNo));
          vh.mContentOneTv.setText(item.getMoutbillNo());
          vh.mTitleTwoTv.setText(getContext().getString(R.string.customerName));
          vh.mContentTwoTv.setText(item.getMcustomerName());
          vh.mTitleThreeTv.setText(getContext().getString(R.string.salesManName));
          vh.mContentThreeTv.setText(item.getMoutappmanName());
          if (mListview.isItemChecked(position + 1)) {//由于有下拉刷新,所以position+1
            vh.mHolderRootView.setBackground(
                getContext().getResources().getDrawable(R.color.gray_rl_click));
          } else {
            vh.mHolderRootView.setBackground(
                getContext().getResources().getDrawable(R.color.white));
          }
        }
      };
      setListAdapter(mAdapter);
      return;
    }

    mAdapter.clear();
    mAdapter.addAll(detail);
    mAdapter.notifyDataSetChanged();
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_confirm, menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

      case R.id.menu_item_confirm:
        SparseBooleanArray checkedItems = mListview.getCheckedItemPositions();
        if (checkedItems != null) {
          //选择后要清空之前的数据.用新建对象的方式清空.
          RProInvoiceRecd receiptDetailUpdate = new RProInvoiceRecd();
          receiptDetailUpdate.setOrderType("out");
          ArrayList<String> ids = new ArrayList<String>();

          ArrayList<String> names = new ArrayList<String>();
          double amount = 0.0;//订单金额.
          double unReceiptAmount = 0.0;//未开票金额.

          for (int i = 0; i < checkedItems.size(); i++) {
            //获取选中数据.
            if (checkedItems.valueAt(i)) {
              rOutappMain select = (rOutappMain) mAdapter.getItem(checkedItems.keyAt(i) - 1);
              names.add(select.getMoutbillNo());
              ids.add(select.getId());
              amount += select.getSumPrice();
              unReceiptAmount += select.getResidualInvoiceAmount();
            }
          }
          receiptDetailUpdate.setOrderId(MyUtils.getJoinString(ids));
          receiptDetailUpdate.setOrderName(MyUtils.getJoinString(names));
          receiptDetailUpdate.setContractAmount(amount);
          receiptDetailUpdate.setMakedInvoiceAmount(unReceiptAmount);
          Intent i = new Intent();
          i.putExtra(ContractPagerActivity.EXTRA_UPDATE_CONTRACT, receiptDetailUpdate);
          getActivity().setResult(Activity.RESULT_OK, i);
          getActivity().finish();
        }

        return true;

      default:
        return super.onOptionsItemSelected(item);
    }
  }

  public void refresh() {
    volleyPost();
  }

  public static BillListFragment newInstance(String customerId) {
    Bundle args = new Bundle();
    args.putString(ContractPagerActivity.EXTRA_CUSTOMER_ID, customerId);
    BillListFragment fragment = new BillListFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
